package com.winit.openapi.ece.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.ContractService;
import com.winit.erp.spi.bpartner.command.ContractCommand;
import com.winit.oms.spi.ece.EceDeliveryService;
import com.winit.oms.spi.ece.command.EceDeliveryCommand;
import com.winit.oms.spi.ece.vo.EceDeliveryResult;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * 发货相关操作处理
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * bing.gu 	1.0  		2015年8月3日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/ece/delivery")
public class EceDeliveryController extends BaseController {

    @Resource
    private ContractService agreementService;

    @Resource
    EceDeliveryService      eceDeliveryService;

    /**
     * 确认发货(支持批量)
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/confirm")
    public String confirm(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 效验用户是否是isp业务用户
        checkIspRight();
        Object obj = requestMsg.getData();
        List<String> list = new ArrayList<String>();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            ValidateUtil.validList(json, "orderNoList", true);
            JSONArray packageList = json.getJSONArray("orderNoList");
            for (Object object : packageList) {
                JSONObject orderNoObj = (JSONObject) object;
                ValidateUtil.validNotNull(orderNoObj, "orderNo");
                ValidateUtil.validMaxLength(orderNoObj, "orderNo", 60);
                list.add(orderNoObj.getString("orderNo").trim());
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 调用接口确认发货
        EceDeliveryCommand command = new EceDeliveryCommand();
        command.setOrderNoList(list);
        EceDeliveryResult result = new EceDeliveryResult();
        result = eceDeliveryService.confirm(command);

        if (null != result) {
            // 返回操作结果
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("successCount", result.getSuccessCount());
            data.put("failedCount", result.getFailedCount());
            data.put("errMsg", StringUtils.isNotBlank(result.getErrMsg()) ? result.getErrMsg() : "");
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.CONFIRM_DELIVERY_FAILD);
        }

        return SUCCESS;
    }

    /**
     * 取消发货(支持批量)
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/cancel")
    public String cancel(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 效验用户是否是isp业务用户
        checkIspRight();
        Object obj = requestMsg.getData();
        List<String> list = new ArrayList<String>();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            ValidateUtil.validList(json, "orderNoList", true);
            JSONArray packageList = json.getJSONArray("orderNoList");
            for (Object object : packageList) {
                JSONObject orderNoObj = (JSONObject) object;
                ValidateUtil.validNotNull(orderNoObj, "orderNo");
                ValidateUtil.validMaxLength(orderNoObj, "orderNo", 60);
                list.add(orderNoObj.getString("orderNo").trim());
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 调用接口取消发货
        EceDeliveryCommand command = new EceDeliveryCommand();
        command.setOrderNoList(list);
        EceDeliveryResult result = new EceDeliveryResult();
         result = eceDeliveryService.cancel(command);
         
        if (null != result) {
            // 返回操作结果
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("successCount", result.getSuccessCount());
            data.put("failedCount", result.getFailedCount());
            data.put("errMsg", StringUtils.isNotBlank(result.getErrMsg()) ? result.getErrMsg() : "");
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.CANCEL_DELIVERY_FAILD);
        }

        return SUCCESS;
    }

    /**
     * 校验用户是不是isp用户
     */
    private void checkIspRight() {
        ContractCommand command = new ContractCommand();
        command.setBusiType("ISP");
        command.setBpartnerId(Long.parseLong(CommandContext.getContext().getUserId()));
        boolean rightStatus = agreementService.isOpenContract(command);

        if (!rightStatus) {
            throw new ApiException(ErrorCode.USERNAME_ISNOT_ISP_USER);
        }
    }
}
